import { postImgData } from "@/api/sign.js";
import { Toast } from "vant";
function datUaRLtoFile(dataurl, filename) {
  const arr = dataurl.split(",");
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}
export default {
  state: {
    imgStr: "",
    face: {
      faceToken: "",
      unitGroup: "",
      userGroup: "",
      username: "",
    },
    flag: false,
  },
  mutations: {
    SET_IMG(state, data) {
      state.imgStr = data;
    },
    CLEAR_IMG(state) {
      state.face = {
        faceToken: "",
        unitGroup: "",
        userGroup: "",
        username: "",
      };
    },
  },
  actions: {
    getdata({ commit, state }, data) {
      commit("SET_IMG", data);

      if (state.imgStr.length != 0) {
        try {
          const getdatas = async () => {
            Toast.loading({
              message: "读取数据中...",
              forbidClick: true,
              duration: 3000,
            });
            let file = datUaRLtoFile(state.imgStr, "one");
            let formdata = new FormData(); // 创建form对象
            formdata.append("multipartFile", file);
            const { data } = await postImgData(formdata);
            console.log(
              "%c 🥞 data: ",
              "font-size:20px;background-color: #42b983;color:#fff;",
              data
            );
            state.face = data;
            // state.flag = data.error_msg;
            // if (state.flag === "SUCCESS") {
            // }

            //state.imgStr = "";
          };
          getdatas();
        } catch {
          Toast.fail({
            message: "上传图片信息出错，请重试！！！",
            duration: 5000,
            closeOnClick: true,
          });
        }
      }
    },
    cleardata({ commit }) {
      commit("CLEAR_IMG");
    },
  },
};
